﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using JEdwonTune.Lib.Jskit;
using System.Text.RegularExpressions;
using System.Xml;
using JEdwonTune.Lib;

namespace JEdwonTune.Jskit {
    public partial class FrmBuildJsPackage : FrmMDIChild {
        public FrmBuildJsPackage() {
            InitializeComponent();
        }
        private String _JskitPath;
        public String JskitPath {
            set { _JskitPath = value; }
            get { return _JskitPath; }
        }


        private void FrmJskitView_Load(object sender, EventArgs e) {
        }

        private void toolStripButton1_Click(object sender, EventArgs e) {
            String lastFolder = loadLastFolder();
            if (!String.IsNullOrEmpty(lastFolder)) {
                this.folderBrowserDialog1.SelectedPath = lastFolder;
            }
            DialogResult dr = this.folderBrowserDialog1.ShowDialog();
            if (dr == DialogResult.OK) {
                _JskitPath = this.folderBrowserDialog1.SelectedPath;
                Ctrls.BindDirFile2Tree(_JskitPath, this.treeView1.Nodes);
                this.tsbtnPackage.Enabled = true;
                if (!_JskitPath.Equals(lastFolder)) {
                    saveLastFolder(_JskitPath);
                }
            }
        }

        private void saveLastFolder(String folder) {
            String filepath = System.Environment.CurrentDirectory + @"\" + MyUtil.OPTION_FILENAME;
            XmlDocument doc = new XmlDocument();
            if (File.Exists(filepath)) {
                doc.Load(filepath);
            } else {
                doc.LoadXml("<?xml version=\"1.0\" encoding=\"utf-8\"?><jskit></jskit>");
            }
            XmlNode node = doc.SelectSingleNode("//build-jspackage-folder");
            if (node == null) {
                node = doc.CreateElement("build-jspackage-folder");
                XmlAttribute attr = doc.CreateAttribute("value");
                attr.Value = folder;
                node.Attributes.Append(attr);
                doc.DocumentElement.AppendChild(node);
            } else {
                node.Attributes["value"].Value = folder;
            }
            doc.Save(filepath);
        }
        private String loadLastFolder() {
            String filepath = System.Environment.CurrentDirectory + "\\" + MyUtil.OPTION_FILENAME;
            XmlDocument doc = new XmlDocument();
            if (File.Exists(filepath)) {
                doc.Load(filepath);
                XmlNode node = doc.SelectSingleNode("//build-jspackage-folder");
                if (node == null) return "";
                else
                    return node.Attributes["value"].Value;
            } else {
                return "";
            }
        }

        private void treeView1_AfterCheck(object sender, TreeViewEventArgs e) {
            if (e.Action != TreeViewAction.Unknown) {
                //Event call by mouse or key-press
                SetNodeCheckStatus(e.Node, e.Node.Checked);
            }
        }
        private void SetNodeCheckStatus(TreeNode tn, bool Checked) {
            if (tn == null) return;
            tn.Expand();
            // Check children nodes
            foreach (TreeNode tnChild in tn.Nodes) {
                tnChild.Checked = Checked;
                SetNodeCheckStatus(tnChild, Checked);
            }
            // Set parent check status
            TreeNode tnParent = tn;
            int nNodeCount = 0;
            while (tnParent.Parent != null) {
                tnParent = (TreeNode)(tnParent.Parent);
                nNodeCount = 0;
                foreach (TreeNode tnTemp in tnParent.Nodes) {
                    if (tnTemp.Checked == Checked)
                        nNodeCount++;
                }
                if (nNodeCount == tnParent.Nodes.Count)
                    tnParent.Checked = Checked;
                else
                    tnParent.Checked = false;
            }

        }
        IList<TreeNode> checkedList = new List<TreeNode>();
        private void loadCheckedNode(TreeNode rNode) {
            if (rNode.Nodes.Count > 0) {
                foreach (TreeNode node in rNode.Nodes) {
                    loadCheckedNode(node);
                }
            } else {
                if (rNode.Checked) {
                    checkedList.Add(rNode);
                }
            }
        }
        private void ShowLog(String msg) {
            this.rtxtView.Text += "\n"+msg;
        }
        private void tsbtnPackage_Click(object sender, EventArgs e) {
            this.saveFileDialog1.Filter = "脚本文件(*.js)|*.js";
            this.saveFileDialog1.FileName = "jskit.package.js";
            DialogResult dr = this.saveFileDialog1.ShowDialog();
            if (dr != DialogResult.OK) {
                return;
            }
            //遍历Treeview
            TreeNodeCollection nodelist = this.treeView1.Nodes;
            foreach (TreeNode node in nodelist) {
                loadCheckedNode(node);
            }
            this.rtxtView.Text = "打包开始：";
            Int32 okCount = 0;
            StringBuilder sb = new StringBuilder();
            StringBuilder log = new StringBuilder();
            foreach (TreeNode node in checkedList) {
                String name = node.Text;
                if(Regex.IsMatch(name,"\\.js$",RegexOptions.IgnoreCase)){
                    String fullPath = (String)node.Tag;
                    ShowLog("[" + (okCount + 1) + "]打包 " + name + ",");
                    ShowLog("  解析 " + fullPath + ",");
                    if (!File.Exists(fullPath)) {
                        ShowLog("/*" + name + " not found*/");
                    } else {
                        sb.Append(JsParser.ParseJsFile2Zipped(name, fullPath));
                    }
                    ShowLog("  完成！");
                    okCount++;
                }
            }
            ShowLog("  共打包了 " + okCount + " 个文件!");
            this.rtxtSelected.Text = sb.ToString();
            try {
                File.WriteAllText(this.saveFileDialog1.FileName, sb.ToString());
            } catch (Exception ex) {
                ShowLog("  保存文件失败：" + ex.Message);
                MessageBox.Show("保存文件失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void tsbtnClose_Click(object sender, EventArgs e) {
            this.Close();
        }
    }
}
